package dragon

import (
	"fmt"
	"http"
	"json"
	"template"

	"appengine"
	"appengine/urlfetch"
)

const moviesFeed = `http://gdata.youtube.com/feeds/api/users/%s/uploads?alt=%s&v=%s&thumbsize=%s`

type movie struct {
	Title string
	Id string
	Thumb string
}

func handleMovies(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	client := urlfetch.Client(c)

	tmpURL := fmt.Sprintf(moviesFeed, ytuser, method,
		apiver, thumbsize)
	resp, _ := client.Get(tmpURL)

	m := make([]movie, 10)
	var d data

	dec := json.NewDecoder(resp.Body)
	dec.Decode(&d)
	resp.Body.Close()

	m = getMovies(&d, m)

	ts := new(template.Set)
	troot, _ := template.New("root").
		Funcs(template.FuncMap{
			"date": stuffDate,
		}).
		ParseFile("templates/root.html")
	tcontent, _ := template.New("content").
		ParseFile("templates/movies.html")
	ts.Add(troot, tcontent)
	ts.Execute(w, "root", map[string]interface{}{"Movies": m, "Site": count(c, r, w),})
}

func getMovies(d *data, m []movie) []movie {
	var k int
	for k = range d.Feed.Entry {
		if k+1 >= cap(m) {
			nm := make([]movie, k*2)
			copy(nm, m)
			m = nm
		} 
		var tmp interface{}

		tmp = d.Feed.Entry[k]["title"]
		m[k].Title = tmp.(map[string]interface{})["$t"].(string)

		tmp = d.Feed.Entry[k]["media$group"]
		m[k].Id = tmp.(map[string]interface{})["yt$videoid"].(
				map[string]interface{})["$t"].(string)

		tmp = d.Feed.Entry[k]["media$group"]
		m[k].Thumb = tmp.(map[string]interface{})["media$thumbnail"].(
				[]interface{})[1].(
				map[string]interface{})["url"].(string)
	}
	m = m[0:k+1]

	return m
}
